require("plugin")

plugin.wikipedia = {
	new = function(p)
		local self = { plugin = p }
		setmetatable(self, { __index = plugin.wikipedia })
		return self
	end,
	
	activate = function(self)
		self:showPage()
	end,
	
	deactivate = function(self)
	end,
	
	check = function(self)
		self.plugin.stoicheia:checkCmd(0, "lynx", "-version")
	end,
	
	controlEvent = function(self, event)
		if event == "back" then
			if self.onweb then
				self.onweb = false
				self:showPage()
			else
				self.plugin.stoicheia:showStartPage()
			end
			return
		end
		if event == "search" then
			self.plugin.stoicheia.gui.pagewin:exec("getValue(\"phrase\");")
			return
		end
		if event == "previous" then
			self.plugin.stoicheia.gui.pagewin:back()
			return
		end
		if event == "next" then
			self.plugin.stoicheia.gui.pagewin:forward()
			return
		end
	end,
	
	hiliteControl = function(self, name, on)
		if name == "search" then return on end
		return true
	end,
	
	pageEvent = function(self, event, arg)
		if event == "VALUE" then
			local segs = arg:split(":")
			local name, value = segs[1], common.urlDecode(segs[2])
			if value == nil then value = "" end
			if name == "phrase" then
				local found = self:search(value)
				self.found = nil
				self.phrase = value
				if type(found) == "string" then
					self:showWeb(found)
				else
					self.found = found
					self:showPage()
				end
				self.plugin.stoicheia:hiliteControlRaw("search", false)
			end
			return
		end
		if event == "CLICKED" then
			self:showWeb(arg)
			return
		end
	end,
	
	showPage = function(self)
		local sw, sh = self.plugin.stoicheia:getScreenSize()
		local gap = math.floor(sh / 5)
		self.plugin.stoicheia:showPage("wikipedia", function(event, f)
			if event == "html" then
				f:renderFormLabel(common.getResource("input_phrase"), nil, gap, sh / 4, sw - (2 * gap))
				f:renderText("phrase", gap, sh / 3, sw - (2 * gap), nil, self.phrase, false)
				if self.found ~= nil then
					if #self.found == 0 then
						local label = string.format(common.getResource("notfound"), self.phrase)
						f:renderFormLabel(label, nil, gap, sh / 2, sw - (2 * gap))
					else
						f:beginList(gap, sh / 2, sw - (2 * gap), sh / 3)
						for i, item in pairs(self.found) do
							f:renderListItem(item.title, item.href, 0)
						end
						f:endList()
					end
				end
				return
			end
			if event == "script" then
				f.r:pe("function onload(){ focus(\"phrase\"); }")
				return
			end
		end)
		self.plugin.stoicheia:setControls(true, "back", "search")
	end,
	
	showWeb = function(self, url)
		self.plugin.stoicheia.gui.pagewin:scroll(true)
		self.plugin.stoicheia:setControls(false, "back", "previous")
		self.plugin.stoicheia.gui.pagewin:clearHistory(1)
		self.plugin.stoicheia.gui.pagewin:open(url)
		self.onweb = true
	end,
	
	search = function(self, phrase)
		assert(type(phrase) == "string")
		local lang = common.getConfig("plugin.wikipedia.language")
		if lang == nil then lang = "en" end
		local urlbase = string.format("http://%s.wikipedia.org", lang)
		if phrase == "" then
			return urlbase
		end
		local url = string.format("%s/wiki/Special:Search?search=%s", urlbase, common.urlEncode(phrase))
		local stream = task.executer("lynx", "-noredir", "-source", url)
		local empty = true
		local results = false
		local items = {}
		for line in stream:lines() do
			empty = false
			string.gsub(line, "<(.-)>", function(tag)
				if tag:indexof("mw-search-results") ~= nil then
					results = true
				end
				if results then
					if tag == "/ul" then
						results = false
					else
						tag:gsub("^a .-href=[\"'](.-)[\"'].-title=[\"'](.-)[\"']", function(href, title)
							items[#items + 1] = {
								href = urlbase .. href,
								title = common.xmlDecode(title)
							}
						end)
					end
				end
			end)
		end
		stream:close()
		if empty then return url end
		return items
	end
}


